import axios from 'axios';

// 超时
const { VITE_ENV, VITE_REQUEST_API, VITE_REQUEST_URL } = import.meta.env;
const service = axios.create({
  timeout: 1000 * 60 * 3,
  baseURL: VITE_ENV === 'development' ? VITE_REQUEST_API : VITE_REQUEST_URL
});

// 请求拦截
service.interceptors.request.use(
  config => {
    const token = sessionStorage.getItem('app-token');
    config.headers['Authorization'] = 'Bearer ' + token;
    return config;
  },
  err => {
    return Promise.reject(err);
  }
);

// 响应拦截
service.interceptors.response.use(
  res => {
    if (res.data.code === 200) {
      return Promise.resolve(res.data);
    } else if ([401, 403].includes(res.data.code)) {
      location.href = '#/login';
      return Promise.reject(res.data);
    } else {
      return Promise.reject(res.data);
    }
  },
  err => {
    return Promise.reject(err);
  }
);

export default service;
